import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/components/Layout.vue'),
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '首页' }
      },
      {
        path: 'locations',
        name: 'Locations',
        component: () => import('@/views/Locations.vue'),
        meta: { title: '地点管理' }
      },
      {
        path: 'locations/pending',
        name: 'LocationsPending',
        component: () => import('@/views/LocationsPending.vue'),
        meta: { title: '地点审核' }
      },
      {
        path: 'ratings',
        name: 'Ratings',
        component: () => import('@/views/Ratings.vue'),
        meta: { title: '评分管理' }
      },
      {
        path: 'dishes',
        name: 'Dishes',
        component: () => import('@/views/Dishes.vue'),
        meta: { title: '推荐菜品管理' }
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('@/views/Users.vue'),
        meta: { title: '用户管理' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('admin_token')
  const requiresAuth = to.matched.some((record) => record.meta.requiresAuth !== false)

  if (requiresAuth && !token) {
    // 需要登录但没有token，跳转到登录页
    next('/login')
  } else if (to.path === '/login' && token) {
    // 已登录用户访问登录页，重定向到首页
    next('/')
  } else {
    next()
  }
})

export default router
